<template>
	<div class="api-preview">
		<a-button :icon="h(EyeOutlined)" :loading="previewing" type="primary" @click="previewApis"> 预览API接口</a-button>

		<!-- API预览模态框 -->
		<a-modal v-model:open="previewModalVisible" :footer="null" title="API接口预览" width="80%">
			<a-table
				:columns="previewColumns"
				:data-source="previewApiList"
				:loading="previewing"
				:pagination="{ pageSize: 10 }"
				size="small"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'method'">
						<a-tag :color="getMethodColor(record.method)">
							{{ record.method }}
						</a-tag>
					</template>
					<template v-if="column.dataIndex === 'requireAuth'">
						<a-tag :color="record.requireAuth ? 'red' : 'green'">
							{{ record.requireAuth ? '需要认证' : '无需认证' }}
						</a-tag>
					</template>
					<template v-if="column.dataIndex === 'module'">
						<a-tag color="blue">{{ record.module }}</a-tag>
					</template>
				</template>
			</a-table>
		</a-modal>
	</div>
</template>

<script setup>
	import { h, ref } from 'vue'
	import { message } from 'ant-design-vue'
	import { EyeOutlined } from '@ant-design/icons-vue'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'

	// Props
	const props = defineProps({
		connectorConfig: {
			type: Object,
			required: true
		}
	})

	// 数据
	const previewing = ref(false)
	const previewModalVisible = ref(false)
	const previewApiList = ref([])

	// 预览表格列定义
	const previewColumns = [
		{
			title: 'API路径',
			dataIndex: 'apiPath',
			width: 200,
			ellipsis: true
		},
		{
			title: '请求方法',
			dataIndex: 'method',
			width: 80,
			align: 'center'
		},
		{
			title: '所属模块',
			dataIndex: 'module',
			width: 100,
			align: 'center'
		},
		{
			title: 'API描述',
			dataIndex: 'apiDescription',
			ellipsis: true
		},
		{
			title: '权限要求',
			dataIndex: 'requireAuth',
			width: 100,
			align: 'center'
		}
	]

	// 预览API列表
	const previewApis = async () => {
		try {
			previewing.value = true

			// 构建预览配置，支持临时配置预览
			const previewConfig = {
				type: 'LOCAL_API',
				config: props.connectorConfig
			}

			// 使用新的预览接口，支持临时配置
			const apiList = await dataConnectorApi.apisWithMetaPreview(previewConfig)
			previewApiList.value = apiList
			previewModalVisible.value = true
		} catch (error) {
			console.error('预览API失败:', error)
			const errorMessage = error.response?.data?.message || error.message || '未知错误'
			message.error('预览API失败：' + errorMessage)
		} finally {
			previewing.value = false
		}
	}

	// 获取请求方法颜色
	const getMethodColor = (method) => {
		const colors = {
			GET: 'green',
			POST: 'blue',
			PUT: 'orange',
			DELETE: 'red',
			PATCH: 'purple'
		}
		return colors[method] || 'default'
	}

	// 暴露方法给父组件
	defineExpose({
		previewApis
	})
</script>

<style scoped>
	.api-preview {
		padding: 0;
	}
</style>
